<?php


namespace app\model;


use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use think\Model;

class CommodityGoods extends Model
{


    /**
     * 商品列表
     * @param $map
     * @param int $type
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function GoodsList($map, $type = 1)
    {
        //默认后台倒叙 1.性价比之王 2.销量 3.积分升序 4.积分倒叙
        switch ($map['sort']) {
            case 1:
                $order = 'sort asc';
                break;
            case  2:
                $order = 'sales desc';
                break;
            case 3:
                $order = 'price asc';
                break;
            case 4:
                $order = 'price desc';
                break;
            default:
                $order = 'sort desc';
        }
        //搜索
        if (!empty($map['search_name'])) {
            $where[] = ['name', 'like', "{$map['search_name']}%"];
        }
        //一级分类
        if (!empty($map['first_class'])) {
            $where[] = ['first_class', '=', $map['first_class']];
        }
        //二级分类
        if (!empty($map['two_class'])) {
            $where[] = ['two_class', '=', $map['two_class']];
        }
        //收藏
        if (!empty($map['collect'])) {
            $where[] = ['id', 'in', $map['collect']];
        }

        //下架
        if ($type == 2 && $map['grounding'] == '1') {
            $where[] = ['grounding', '=', 0];
        } else {
            $where[] = ['grounding', '=', 1];
        }
        $where[] = ['status', '=', 1];
        $where[] = ['condition', '=', 1];
        $where[] = ['channel', '=', 1];
        //最开始产品设计有问题 不能查询到金额商品 所以后期只有使用not IN
        $goods_list = Db::name('commodity_goods')
            ->field("id,name,sn,first_class,two_class,m_id,image,images,price,original_price,cost,grounding,stock,warning,origin,output_time,brand,series,for_people,content,sort,comment,intro,sales,FROM_UNIXTIME(created_time,'%Y-%m-%d %h:%i:%s') as created_time")
            ->withAttr('comment', function ($value, $data) {
                if (empty($value)) {
                    return [];
                } else {
                    return explode(',', $value);
                }
            })
            ->where($where)
            ->order($order)
            ->paginate($map['limit'])
            ->toArray();
        if ($type == 2 && !empty($goods_list['data'])) {
            foreach ($goods_list['data'] as &$b) {
                //查看搜藏人数
                $b['collect_num'] = Cache::store('redis')->SCARD('Collect_' . $b['id']);
            }
        }
        return app('json')->json_success('成功', $goods_list ?: []);
    }


    /**
     * 专区商品列表
     * @param $map
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function SpecialGoodsList($map)
    {

        if (!empty($map['type'])) {
            $where[] = ['a.type', '=', $map['type']];
        }
        switch ($map['cls']) {
            case 1://农特优选
                $db_name = 'commodity_special';
                if (!empty($map['address'])) {
                    $where[] = ['a.address', 'like', "{$map['address']}%"];
                }
                break;
            case  2://助力实体
                $db_name = 'commodity_entity';

                break;
            case 3://私定精选
                $db_name = 'commodity_selection';
                break;
            case 4://医疗健康
                $db_name = 'commodity_health';
                if (!empty($map['type_one'])) {
                    $where[] = ['a.type_one', '=', $map['type_one']];
                }
                if (!empty($map['type_two'])) {
                    $where[] = ['a.type_two', '=', $map['type_two']];
                }
                break;
            case 5://抽奖
                $db_name = 'commodity_lottery';
                if (!empty($map['lottery_type'])) {
                    $where[] = ['a.type', '=', $map['lottery_type']];
                }
                break;
        }
        //搜索
        if (!empty($map['search_name'])) {
            $where[] = ['b.name', 'like', "{$map['search_name']}%"];
        }
        $where[] = ['b.status', '=', 1];
        $where[] = ['b.grounding', '=', 1];
        $where[] = ['b.condition', '=', 1];
//        var_dump($db_name);
        $goods_list = Db::name($db_name)
            ->alias('a')
            ->leftJoin('commodity_goods b', 'a.goods_id = b.id')
            ->field("b.id,name,b.sn,first_class,two_class,b.m_id,image,images,price,original_price,cost,grounding,stock,warning,origin,output_time,brand,series,for_people,content,a.sort,comment,intro,b.sales,a.created_time")
            ->where($where)
            ->order('a.sort desc')
            ->paginate($map['limit'])
            ->toArray();
        return app('json')->json_success('成功', $goods_list ?: []);
    }


    /**
     * 秒杀商品列表
     * @param $map
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function SpikeList($map)
    {
        $redis = Cache::store('redis');
        $goods_list = Db::name('commodity_spike')
            ->alias('a')
            ->leftJoin('commodity_goods b', 'a.goods_id = b.id')
            ->field("b.id,name,b.sn,b.first_class,b.two_class,b.m_id,b.image,b.images,a.price,a.spike_price,a.value,a.spike_num,b.grounding,b.warning,b.origin,b.output_time,b.brand,b.series,b.for_people,b.content,a.sort,b.comment,b.intro,b.sales,a.created_time,a.id as spike_id,a.total_num")
            ->where(['spike_t_id' => $map['type']])
            ->order('a.sort desc')
            ->paginate($map['limit'])
            ->toArray();
        if (!empty($goods_list['data'])) {
            foreach ($goods_list['data'] as &$v) {
                $goods_number_key = "Goods" . $v['spike_id'] . '_' . date('Y-m-d', time());
                $gnRedis = $redis->llen("$goods_number_key");
                $v['lave'] = $gnRedis ?: 0;
            }
        }
        $goods_list['time'] = date('H');
        return app('json')->json_success('成功', $goods_list ?: []);

    }


    /**
     * 商品详情
     * @param $data
     * @param $goods
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function GoodsDetails($data, $goods)
    {
        $merchant = app()->make(Merchant::class)->where(['id' => $goods['m_id']])->find();
        $goods['merchant_name'] = $merchant['name'];
        $goods['merchant_avatar'] = $merchant['image'];
        $goods['spec_relation'] = CommoditySpecRelation::
        field('spec_name,spec_value')
            ->where(['goods_id' => $goods['id']])
            ->withAttr('spec_value', function ($value) {
                return json_decode($value, true);
            })->select()
            ->toArray();
        $goods['spec'] = CommoditySpec::
        where(['goods_id' => $goods['id']])
            ->select()
            ->toArray();
        return app('json')->json_success('成功', $goods ?: []);
    }


    /**
     * 商品图片
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function LotteryImages($data)
    {
        $result = Db::name('commodity_lottery')
            ->alias('a')
            ->leftJoin('commodity_goods b', 'a.goods_id = b.id')
            ->field('b.image,a.type')
            ->select()
            ->toArray();
        $arr = [];
        if (!empty($result)) {
            foreach ($result as &$v) {
                switch ($v['type']) {
                    case 1:
                        $arr['one'][] = $v;
                        break;
                    case 2:
                        $arr['two'][] = $v;
                        break;
                    case 3:
                        $arr['three'][] = $v;
                        break;
                    case 4:
                        $arr['four'][] = $v;
                        break;
                    default:
                        $arr['five'][] = $v;

                }
            }
            return app('json')->json_success('成功', $arr);
        }
    }
}